import React, { useEffect, useImperativeHandle, useRef } from 'react';

import PropTypes from 'prop-types';
import { useLocalStorage } from 'react-use';

import { useCurrentUser, useRequest } from '@/hooks';
import { Guide } from '@/molecules';
import { confirmFlag, queryEmployeeFlagByType } from '@/services/user';

/**
 * 引导组件, 根据服务端的相关状态标记来决定是否启动
 */
const GuideByServerFlag = React.forwardRef((props, ref) => {
    const { manual, serverStorageKey, children, ...otherProps } = props;
    const { employeeCode } = useCurrentUser();
    const [guideFlag, setGuideFlag] = useLocalStorage(`guide-${serverStorageKey}-${employeeCode}`, false);
    // 获取引导的flag
    const { data: enable, mutate } = useRequest(() => queryEmployeeFlagByType(employeeCode, serverStorageKey), {
        ready: !!employeeCode && guideFlag !== true,
        formatResult: res => {
            if (res) {
                const { code, data } = res;
                if (code === 10000) {
                    if (data) {
                        setGuideFlag(true);
                    }
                    return !data;
                }
            }
            return false;
        }
    });
    // 标记当前引导为已读
    const { run: stopGuide } = useRequest(() => confirmFlag(employeeCode, serverStorageKey), {
        manual: true
    });
    const guideRef = useRef();

    // 停止引导
    const handleStop = () => {
        stopGuide().then(() => {
            // 手动修改状态, 防止重复 start
            mutate(false);
            setGuideFlag(true);
        });
    };

    useEffect(() => {
        // 非手动模式且服务端没有相关标记, 就直接开启引导
        if (!manual && enable && !guideFlag) {
            guideRef.current.start();
        }
    }, [enable, guideFlag, manual]);

    // 手动模式下暴露的方法
    useImperativeHandle(ref, () => ({
        start: () => {
            if (enable) {
                guideRef.current.start();
            }
        },
        stop: () => {
            guideRef.current.stop();
            mutate(false);
        }
    }));

    return (
        <Guide ref={guideRef} autoStart={false} onStop={handleStop} {...otherProps}>
            {children}
        </Guide>
    );
});

GuideByServerFlag.propTypes = {
    manual: PropTypes.bool,
    serverStorageKey: PropTypes.string
};

GuideByServerFlag.defaultProps = {
    manual: false,
    serverStorageKey: ''
};
GuideByServerFlag.displayName = 'GuideByServerFlag';
GuideByServerFlag.Step = Guide.Step;

export default GuideByServerFlag;
